package stockblaster.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import stockblaster.gen.R;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainPageActivity extends Activity {
	final Activity thisAct = MainPageActivity.this;
	Button summaryBut, portfolioBut, newsBut, searchBut, logOutBut;
	Button objectiveBut, helpBut, advanceOneBut; // advanceTwoBut;
	Button usernameBut; 
	
	TextView totalAssetsTV, stockValueTV, uninvestedTV; // valueChangeOverTV;
	TextView monthYearTV, emptyPortfolioTV, emptyNewsTV;
	TextView gainLossTV;

	// Spinner vcoSpinner;

	LinearLayout summaryBridge, portfolioBridge, newsBridge, searchBridge;
	LinearLayout newsViewBox;
	ScrollView summaryScrollView, newsScrollView;
	ListView portfolioLV, searchLV;

	ArrayList<CompanySearchViewData> portfolioList;
	ArrayList<CompanySearchViewData> searchList;

	int newsSize = 0, portfolioSize = 0;
	
	public static boolean first_time;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_view);

		CurrentUser.current_class = MainPageActivity.class;

		summaryBut = (Button) this.findViewById(R.id.button1);
		portfolioBut = (Button) this.findViewById(R.id.button2);
		newsBut = (Button) this.findViewById(R.id.button3);
		searchBut = (Button) this.findViewById(R.id.button4);
		logOutBut = (Button) this.findViewById(R.id.button5);
		advanceOneBut = (Button) this.findViewById(R.id.advance1month);
		// advanceTwoBut = (Button) this.findViewById(R.id.advance2months);
		// advanceTwoBut.setEnabled(false);

		objectiveBut = (Button) this.findViewById(R.id.objectiveButton);
		helpBut = (Button) this.findViewById(R.id.helpButton);
		// helpBut.setEnabled(false);

		totalAssetsTV = (TextView) this.findViewById(R.id.textView3);
		stockValueTV = (TextView) this.findViewById(R.id.textView5);
		uninvestedTV = (TextView) this.findViewById(R.id.textView7);
		// valueChangeOverTV = (TextView) this.findViewById(R.id.textView9);
		// noStockTV = (TextView) this.findViewById(R.id.noStockText);
		usernameBut = (Button) this.findViewById(R.id.textView10);
		if (CurrentUser.isLoggedIn())
			usernameBut.setText(CurrentUser.getUsername());

		monthYearTV = (TextView) this.findViewById(R.id.monthYear);
		monthYearTV.setText("" + CurrentUser.getMonth() + "/"
				+ CurrentUser.getYear());

		emptyPortfolioTV = (TextView) this
				.findViewById(R.id.emptyPortfolioText);
		emptyNewsTV = (TextView) this.findViewById(R.id.emptyNewsText);
		emptyPortfolioTV.setVisibility(View.GONE);
		emptyNewsTV.setVisibility(View.GONE);

		summaryBridge = (LinearLayout) this.findViewById(R.id.summaryBridge);
		portfolioBridge = (LinearLayout) this
				.findViewById(R.id.portfolioBridge);
		newsBridge = (LinearLayout) this.findViewById(R.id.newsBridge);
		searchBridge = (LinearLayout) this.findViewById(R.id.searchBridge);
		newsViewBox = (LinearLayout) this.findViewById(R.id.newsViewBox);
		newsViewBox.removeAllViews();

		summaryScrollView = (ScrollView) this
				.findViewById(R.id.summaryScrollView);
		newsScrollView = (ScrollView) this.findViewById(R.id.newsScrollView);

		portfolioLV = (ListView) this.findViewById(R.id.portfolioListView);
		searchLV = (ListView) this.findViewById(R.id.searchListView);

		// initSpinners();

		Double stockValue = CurrentUser.getTotalStockValue();
		stockValueTV.setText(MethodHelper.twoDecimal(stockValue));

		Double totalAssets = CurrentUser.getTotalAssets();
		totalAssetsTV.setText(MethodHelper.twoDecimal(totalAssets));

		Double uninvested = CurrentUser.getFund();
		uninvestedTV.setText(MethodHelper.twoDecimal(uninvested));

		initListViews();
		setNews();
		setOnClickListener();

		setVisibilityAndEnability();

		if (CurrentUser.getUsername().equals("Januardo Jankowski")) {
			if (portfolioBut.isSelected()) {
				if (CurrentUser.getHelpNum() == 3)
					dialogPopUps(true);
			}
			objectiveBut.setText("Objectives");
		} else {
			if (first_time) {
				MethodHelper.showUserProfileDialog(thisAct, getResources());
				//CurrentUser.checkObjective(thisAct);
			}
		}
	}

	public void setVisibilityAndEnability() {
		if (CurrentUser.getUsername().equals("Januardo Jankowski")) {
			if (CurrentUser.getMonth() > 1) {
				advanceOneBut.setEnabled(true);
				monthAdvancedPopUps();
			} else if ((CurrentUser.getHelpNum() < 5)) {
				advanceOneBut.setEnabled(false);
			}
		}

		switch (CurrentUser.currentMainTab) {
		case 1:
			setSummarySelected(View.VISIBLE);
			break;
		case 2:
			setPortfolioSelected(View.VISIBLE);
			break;
		case 3:
			setNewsSelected(View.VISIBLE);
			break;
		case 4:
			setSearchSelected(View.VISIBLE);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		MethodHelper.show_dialogs(MainPageActivity.this, SplashActivity.class,
				MethodHelper.LOG_OUT);
	}

	@Override
	public void onResume() {
		super.onResume();
		newsViewBox.removeAllViews();
		initListViews();
		setNews();
		monthYearTV.setText("" + CurrentUser.getMonth() + "/"
				+ CurrentUser.getYear());
		dialogPopUps(false);
		setVisibilityAndEnability();
		Double stockValue = CurrentUser.getTotalStockValue();
		stockValueTV.setText(MethodHelper.twoDecimal(stockValue));

		Double totalAssets = CurrentUser.getTotalAssets();
		totalAssetsTV.setText(MethodHelper.twoDecimal(totalAssets));

		Double uninvested = CurrentUser.getFund();
		uninvestedTV.setText(MethodHelper.twoDecimal(uninvested));
//		if (!CurrentUser.getUsername().equals("Januardo Jankowski")) {
//			CurrentUser.checkObjective(thisAct);
//		}
	}

	private void initListViews() {
		// Portfolio
		portfolioList = new ArrayList<CompanySearchViewData>();

		final LinkedList<String> userCompanyNames = CurrentUser
				.getCompanyNames();
		int size = userCompanyNames.size();
		String[] cNames = new String[size];
		int[] cLogo = new int[size];
		int[] cArrow = new int[size];
		Double[] cGrowth = new Double[size];
		Double[] sPrice = new Double[size];
		int[] sOwned = new int[size];
		Double[] totalValue = new Double[size];
		Double[] gainLoss = new Double[size];
		for (int i = 0; i < userCompanyNames.size(); ++i) {
			cNames[i] = userCompanyNames.get(i).toString();
			cLogo[i] = Companies.getCompanyLogo(cNames[i]);
			cArrow[i] = Companies.getArrow(cNames[i]);
			cGrowth[i] = Companies.getCompanyPercentGrowth(cNames[i]);
			sPrice[i] = Companies.getCompanyShareValue(cNames[i]);
			sOwned[i] = CurrentUser.getShare(cNames[i]);
			totalValue[i] = sOwned[i] * sPrice[i];

			CurrentUser.updateGainLoss(CurrentUser.getMonth(), cNames[i],
					totalValue[i]);
			Double difference = 0.00;
			if (CurrentUser.getMonth() > 1) {
				Double previousValue = 0.00;
				if (CurrentUser.gainLoss
						.containsKey(CurrentUser.getMonth() - 1)) {
					if (CurrentUser.gainLoss.get(CurrentUser.getMonth() - 1)
							.containsKey(cNames[i])) {
						previousValue = CurrentUser.gainLoss.get(
								CurrentUser.getMonth() - 1).get(cNames[i]);
						difference = totalValue[i] - previousValue;
					} else {
						difference = 0.00;
					}
				}
			} else {
				Double previousValue = 0.00;
				if (CurrentUser.gainLoss.containsKey(12)) {
					if (CurrentUser.gainLoss.get(12).containsKey(cNames[i])) {
						previousValue = CurrentUser.gainLoss.get(12).get(
								cNames[i]);
						difference = totalValue[i] - previousValue;
					} else {
						difference = 0.00;
					}
				}
			}
			gainLoss[i] = difference;

			CompanySearchViewData temp = new CompanySearchViewData(cNames[i],
					cLogo[i], cArrow[i], cGrowth[i], sPrice[i], sOwned[i],
					totalValue[i], gainLoss[i]);
			portfolioList.add(temp);
		}

		SearchAdapter adapter = new SearchAdapter(this, portfolioList, true);
		portfolioLV.setAdapter(adapter);

		portfolioLV
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> adapter, View view,
							final int position, long arg) {
						CurrentUser.setCompanyPick(userCompanyNames
								.get(position));
						MethodHelper.switch_activity(MainPageActivity.this,
								CompanyStockInfoActivity.class, false);
					}
				});

		portfolioSize = size;

		// search
		searchList = new ArrayList<CompanySearchViewData>();
		final LinkedList<String> companyNames = Companies.getCompanyNames();
		size = companyNames.size();
		cNames = new String[size];
		cLogo = new int[size];
		cArrow = new int[size];
		cGrowth = new Double[size];
		sPrice = new Double[size];
		sOwned = new int[size];
		for (int i = 0; i < companyNames.size(); ++i) {
			cNames[i] = companyNames.get(i).toString();
			cLogo[i] = Companies.getCompanyLogo(cNames[i]);
			cArrow[i] = Companies.getArrow(cNames[i]);
			cGrowth[i] = Companies.getCompanyPercentGrowth(cNames[i]);
			sPrice[i] = Companies.getCompanyShareValue(cNames[i]);
			sOwned[i] = CurrentUser.getShare(cNames[i]);
			CompanySearchViewData temp = new CompanySearchViewData(cNames[i],
					cLogo[i], cArrow[i], cGrowth[i], sPrice[i], sOwned[i],
					0.00, 0.00);
			searchList.add(temp);
		}

		adapter = new SearchAdapter(this, searchList, false);
		searchLV.setAdapter(adapter);

		searchLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapter, View view,
					final int position, long arg) {
				CurrentUser.setCompanyPick(companyNames.get(position));
				CurrentUser.setFromClass(MainPageActivity.class,
						CurrentUser.COMPANY_INFO);
				MethodHelper.switch_activity(MainPageActivity.this,
						CompanyStockInfoActivity.class, false);
			}
		});
	}

	private void setNews() {
		LinkedList<String> headline = Companies.getCompanyNewsHeadlines();
		HashMap<String, String> hlContent = Companies.getHeadlineContent();
		int max = headline.size();
		int j = 1;
		RelativeLayout layout;
		LayoutParams lp;

		newsSize = max;
		
		int actualNewsNum = 0;
		for (int i = 0; i < max; ++i) {
			// String cName = namesTemp.get(i);
			// set up the layout so we can position them nicely
			layout = new RelativeLayout(this);
			layout.setId(j);
			layout.setClickable(true);
			final String hl = headline.get(i);
			if (hl.equals(""))
				continue;
			++actualNewsNum;
			// text view for headline
			final TextView tv = new TextView(this);
			tv.setId(j + 1);
			tv.setText(hl);
			tv.setTextColor(Color.CYAN);
			tv.setTextSize(25);
			layout.setPadding(5, 5, 0, 0);
			lp = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			layout.addView(tv, lp);

			// text view for content
			final TextView tv1 = new TextView(this);
			tv1.setId(j + 2);
			tv1.setText(hlContent.get(hl));
			tv1.setTextColor(Color.WHITE);
			tv1.setTextSize(18);
			layout.setPadding(0, 5, 0, 0);
			lp = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			lp.addRule(RelativeLayout.BELOW, tv.getId());
			layout.addView(tv1, lp);

			// this is the divider line
			final View v = new View(this);
			v.setBackgroundColor(Color.WHITE);
			v.setLayoutParams(new LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT, 1));

			newsViewBox.addView(layout);
			newsViewBox.addView(v);
		}
		
		if (actualNewsNum == 0) {
			//emptyNewsTV.setVisibility(View.VISIBLE);
			newsSize = 0;
		} else
			emptyNewsTV.setVisibility(View.GONE);

		newsScrollView.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (CurrentUser.getUsername().equals("Januardo Jankowski")) {
					if (newsScrollView.getScrollY() <= newsScrollView
							.getBottom()) {
						if (CurrentUser.getHelpNum() == 6)
							dialogPopUps(true);
					}
					return false;
				}
				return false;
			}
		});

	}

	private void dialogPopUps(boolean isInPage) {
		if (CurrentUser.getUsername().equals("Januardo Jankowski")) {
			int num = CurrentUser.getHelpNum();
			if (isInPage) {
				switch (num) {
				case 3:
					MethodHelper.show_dialogs(MainPageActivity.this,
							MainPageActivity.class, num);
					CurrentUser.addHelpNum();
					break;
				case 6:
					MethodHelper.show_dialogs(MainPageActivity.this,
							MainPageActivity.class, num);
					CurrentUser.addHelpNum();
					break;
				case 7:
//					MethodHelper.show_dialogs(MainPageActivity.this,
//							MainPageActivity.class, num);
					//CurrentUser.addHelpNum();
					break;
				}
			} else {
				switch (num) {
				case 0:
					MethodHelper.show_dialogs(MainPageActivity.this,
							MainPageActivity.class, num);
					CurrentUser.addHelpNum();
					break;
				}
			}
		}
		/*
		 * switch(num) { case 6:
		 * MethodHelper.show_dialogs(MainPageActivity.this,
		 * MainPageActivity.class, num); break; default: break; }
		 */
	}

	private void monthAdvancedPopUps() {
		if (CurrentUser.getUsername().equals("Januardo Jankowski")) {
			int num = CurrentUser.getHelpNum();
			switch (num) {
			case 5:
				MethodHelper.show_dialogs(MainPageActivity.this,
						MainPageActivity.class, num);
				CurrentUser.addHelpNum();
				break;
			}
		}
	}

	private void setSummarySelected(int visibility) {
		if (visibility == View.VISIBLE) {
			emptyPortfolioTV.setVisibility(View.GONE);
			emptyNewsTV.setVisibility(View.GONE);
			CurrentUser.currentMainTab = 1;
			summaryBut.setSelected(true);
			summaryBridge.setVisibility(View.VISIBLE);
			summaryScrollView.setVisibility(View.VISIBLE);
			portfolioBut.setSelected(false);
			portfolioBridge.setVisibility(View.INVISIBLE);
			portfolioLV.setVisibility(View.INVISIBLE);
			newsBut.setSelected(false);
			newsBridge.setVisibility(View.INVISIBLE);
			newsScrollView.setVisibility(View.INVISIBLE);
			searchBut.setSelected(false);
			searchBridge.setVisibility(View.INVISIBLE);
			searchLV.setVisibility(View.INVISIBLE);
		}
	}

	private void setPortfolioSelected(int visibility) {
		if (visibility == View.VISIBLE) {
			if (portfolioSize == 0)
				emptyPortfolioTV.setVisibility(View.VISIBLE);
			emptyNewsTV.setVisibility(View.GONE);
			CurrentUser.currentMainTab = 2;
			summaryBut.setSelected(false);
			summaryBridge.setVisibility(View.INVISIBLE);
			summaryScrollView.setVisibility(View.INVISIBLE);
			portfolioBut.setSelected(true);
			portfolioBridge.setVisibility(View.VISIBLE);
			portfolioLV.setVisibility(View.VISIBLE);
			newsBut.setSelected(false);
			newsBridge.setVisibility(View.INVISIBLE);
			newsScrollView.setVisibility(View.INVISIBLE);
			searchBut.setSelected(false);
			searchBridge.setVisibility(View.INVISIBLE);
			searchLV.setVisibility(View.INVISIBLE);
		}
	}

	private void setNewsSelected(int visibility) {
		if (visibility == View.VISIBLE) {
			emptyPortfolioTV.setVisibility(View.GONE);
			if (newsSize == 0)
				emptyNewsTV.setVisibility(View.VISIBLE);
			CurrentUser.currentMainTab = 3;
			summaryBut.setSelected(false);
			summaryBridge.setVisibility(View.INVISIBLE);
			summaryScrollView.setVisibility(View.INVISIBLE);
			portfolioBut.setSelected(false);
			portfolioBridge.setVisibility(View.INVISIBLE);
			portfolioLV.setVisibility(View.INVISIBLE);
			newsBut.setSelected(true);
			newsBridge.setVisibility(View.VISIBLE);
			newsScrollView.setVisibility(View.VISIBLE);
			searchBut.setSelected(false);
			searchBridge.setVisibility(View.INVISIBLE);
			searchLV.setVisibility(View.INVISIBLE);
		}
	}

	private void setSearchSelected(int visibility) {
		if (visibility == View.VISIBLE) {
			emptyPortfolioTV.setVisibility(View.GONE);
			emptyNewsTV.setVisibility(View.GONE);
			CurrentUser.currentMainTab = 4;
			summaryBut.setSelected(false);
			summaryBridge.setVisibility(View.INVISIBLE);
			summaryScrollView.setVisibility(View.INVISIBLE);
			portfolioBut.setSelected(false);
			portfolioBridge.setVisibility(View.INVISIBLE);
			portfolioLV.setVisibility(View.INVISIBLE);
			newsBut.setSelected(false);
			newsBridge.setVisibility(View.INVISIBLE);
			newsScrollView.setVisibility(View.INVISIBLE);
			searchBut.setSelected(true);
			searchBridge.setVisibility(View.VISIBLE);
			searchLV.setVisibility(View.VISIBLE);
		}
	}

	private void setOnClickListener() {
		summaryBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (!summaryBut.isSelected()) {
					setSummarySelected(View.VISIBLE);
				}
			}
		});

		portfolioBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (!portfolioBut.isSelected()) {
					setPortfolioSelected(View.VISIBLE);
					if (CurrentUser.getHelpNum() == 3)
						dialogPopUps(true);
				}
			}
		});

		newsBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (!newsBut.isSelected()) {
					setNewsSelected(View.VISIBLE);
					// if (CurrentUser.getHelpNum() == 6)
					// dialogPopUps(true);
				}
			}
		});

		searchBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (!searchBut.isSelected()) {
					setSearchSelected(View.VISIBLE);
				}
			}
		});

		logOutBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				MethodHelper.show_dialogs(MainPageActivity.this,
						SplashActivity.class, MethodHelper.LOG_OUT);
			}
		});

		objectiveBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				CurrentUser.setFromClass(MainPageActivity.class,
						CurrentUser.OBJECTIVE);
				MethodHelper.switch_activity(MainPageActivity.this,
						ObjectiveActivity.class, false);
			}
		});

		helpBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				CurrentUser.setFromClass(MainPageActivity.class,
						CurrentUser.HELP);
				MethodHelper
						.switch_activity(thisAct, HelpActivity.class, false);

			}
		});

		advanceOneBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Companies.resetNewsData();
				CurrentUser.addMonth();
				UserRounds.updateCompanies();
				// MethodHelper.switch_activity(MainPageActivity.this,
				// MainPageActivity.class, false);
				MainPageActivity.this.onResume();
			}
		});
		
		usernameBut.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				MethodHelper.showUserProfileDialog(thisAct, getResources());
			}
		});

		// advanceTwoBut.setOnClickListener(new View.OnClickListener() {
		// public void onClick(View v) {
		// }
		// });
	}

	/**
	 * Method to initialize the spinners for countries and currencies
	 */
	@SuppressWarnings("unused")
	private void initSpinners() {
		/*
		 * vcoSpinner = (Spinner) this.findViewById(R.id.spinner1);
		 * ArrayAdapter<CharSequence> countryAdapter =
		 * ArrayAdapter.createFromResource( this, R.array.country_array,
		 * android.R.layout.simple_spinner_item);
		 * countryAdapter.setDropDownViewResource
		 * (android.R.layout.simple_spinner_dropdown_item);
		 * vcoSpinner.setAdapter(countryAdapter);
		 */
	}
}
